
let isAdmin = false;

// 如果是在线模式，则需要在mainthisrt中读取并刷新状态
module.exports = {
    isTest: false, // 是否处于测试环境
    isQQ: cc.sys.browserType == cc.sys.BROWSER_TYPE_QQ_PLAY,
    
    isAdmin(){
        return isAdmin;
    },


    playAudioBK(audio){
        if(!this.canPlayAudio) return;
        if(!this.sounds){
            this.sounds = {};
        }
        if(!this.sounds[audio]){
            this.sounds[audio] = BK.createAudioContext();
            this.sounds[audio].src = `GameRes://sounds/${audio}.mp3`;
        }

        this.sounds[audio].play();
    },

    // 环境部分
    log(data){
        if(this.isQQ){
            BK.Script.log(0,0,data);
        }else{
            console.log(data);
        }
    },

    share(summary,success,fail){
        if(!this.isQQ) return;

        let shareInfo = {
            summary: summary?summary:"一起游戏一气呵成",
            picUrl: 'http://hudong.qq.com/docs/engine/img/848B76B5530AA7EE7B38E9A1267D7086.png',
        }

        BK.QQ.share(shareInfo, (retCode, shareDest, isFirstShare) => {
            BK.Script.log(1, 1, "retCode:" + retCode + " shareDest:" + shareDest + " isFirstShare:" + isFirstShare);
            if(retCode == 0) { //分享成功
                if(success) success();
            } else {
                if(fail) fail();
            }
        });
    },

    increaseCoin(n){
        this.coinNumber += n;
        localStorage.setItem("coinNumber",this.coinNumber);
    },

    showStaticAD(){
        if(!this.isQQ) return;

        BK.Advertisement.fetchBannerAd((retCode, msg, adBannerHandler) => {
            if(retCode == 0) {
                adBannerHandler.show((succCode, msg, handle) => {
                });

                adBannerHandler.onClickClose(function () {
                });
            }
        });
    },

    addWatchVideoTimes(){
        this.watchVideoTimes++;
        localStorage.setItem("watchVideoTimes",this.watchVideoTimes);
    },

    showVideoAD(callback){
        if(!this.isQQ) return;
        
        BK.Advertisement.fetchVideoAd(0, (retCode, msg, handle) => {
            if(retCode == 0) {
                handle.setEventCallack(
                    (code,msg) => {
                    }, //关闭游戏
                    (code,msg) => {//达到看广告时长要求，可以下发奖励
                        if(callback) callback();
                    },
                    (code,msg) => {//关闭视频webview
                    },
                    (code,msg) => {//开始播放视频
                    }
                );
                handle.jump();
            } else {
                BK.Script.log(0, 0, "msg=" + msg);
            }
        })
    },

    saveRankData(startMs,score,callback){
        console.log("saveRankData 1");
        if(this.isQQ){
            console.log("saveRankData 2");
            let mostChapterNumber = this.bigChapterIndex * 15 + this.smallChapterIndex;
            console.log(score);
            console.log(mostChapterNumber);
            if(score > mostChapterNumber){
                // 必须配置好周期规则后，才能使用数据上报和排行榜功能
                BK.QQ.uploadScoreWithoutRoom(1, {
                    userData: [
                        {
                            openId: GameStatusInfo.openId,
                            startMs,    //必填，游戏开始时间，单位为毫秒，字符串类型
                            endMs: ((new Date()).getTime()).toString(),  //必填，游戏结束时间，单位为毫秒，字符串类型
                            scoreInfo: {    // 存放排名信息的对象
                                score
                            },
                        },
                    ],

                    // type 描述附加属性的用途
                    // order 排序的方式
                    // 1: 从大到小，即每次上报的分数都会与本周期的最高得分比较，如果大于最高得分则覆盖，否则忽略
                    // 2: 从小到大，即每次上报的分数都会与本周期的最低得分比较，如果低于最低得分则覆盖，否则忽略
                    // 3: 累积，即每次上报的积分都会累积到本周期已上报过的积分上（本质上是从大到小的一种特例）
                    // 4: 直接覆盖，每次上报的积分都会将本周期的得分覆盖，不管大小

                    attr: {  // attr 配合 scoreInfo
                        score: {   
                            type: 'rank',
                            order: 4,
                        },
                    },
                }, (errCode, cmd, data)=>{
                    // 返回错误码信息
                    if (errCode !== 0) {
                        BK.Script.log(1,1,'上传分数失败!错误码：' + errCode);
                    }else{
                        BK.Script.log(0,0,"uploadScore SUCCESS!");
                        if(callback) callback();
                    }
                });
            }else{
                if(callback) callback();
            }
        }

        if(this.smallChapterIndex == 14){
            this.bigChapterIndex++;
            this.bigChapterNumber++;

            this.smallChapterIndex = 0;
            this.smallChapterNumber = 1;

        }else{
            this.smallChapterIndex++;
            this.smallChapterNumber++
        }
        localStorage.setItem("bigChapterIndex", this.bigChapterIndex);
        localStorage.setItem("smallChapterIndex", this.smallChapterIndex);
    },


    getUserData(){
        if(this.isAdmin()) return;
        // localStorage.clear();

        let hour = 60 * 60 * 1000;
        let lastLoginTime = localStorage.getItem("loginTime");
        let thisLoginTime = new Date().getTime();
        let apartTime, times;
        if(lastLoginTime){
            apartTime = thisLoginTime - lastLoginTime;
            times = Math.round(apartTime / hour);
        }
        localStorage.setItem("loginTime",thisLoginTime);

        let watchVideoTimes = localStorage.getItem("watchVideoTimes");
        if(watchVideoTimes){
            this.watchVideoTimes = watchVideoTimes;
            if(times){
                this.watchVideoTimes -= times;
                if(this.watchVideoTimes < 0){
                    this.watchVideoTimes = 0;
                }
                localStorage.setItem("watchVideoTimes",this.watchVideoTimes);
            }
        }else{
            localStorage.setItem("watchVideoTimes",0);
            this.watchVideoTimes = 0;
        }

        let coinNumber = localStorage.getItem("coinNumber");
        if(coinNumber){
            this.coinNumber = coinNumber;
        }
        let perfectNumber = localStorage.getItem("perfectNumber");
        if(perfectNumber){
            this.perfectNumber = perfectNumber;
        }
        let bigChapterIndex = localStorage.getItem("bigChapterIndex");
        if(bigChapterIndex){
            this.bigChapterIndex = bigChapterIndex;
        }
        let smallChapterIndex = localStorage.getItem("smallChapterIndex");
        if(smallChapterIndex){
            this.smallChapterIndex = smallChapterIndex;
        }
        let perfectChapters = JSON.parse(localStorage.getItem("perfectChapters"));
        if(perfectChapters){
            this.perfectChapters = perfectChapters;
        }
    },



    watchVideoTimes:0, // 今日看视频的次数

    perfectChapters:{}, // 完美过关的小关

    isFirstIn: true, // 是否是最近第一次进入游戏
    canPlayAudio: true,



    // userdata
    coinNumber: isAdmin?10000:0, //用户金币数量
    perfectNumber: 0,//玩家所获得的完美过大关数

    bigChapterIndex: isAdmin?100:0,  // 玩家最高达到的大关下标： 0的话，就是指第一大关
    smallChapterIndex: isAdmin?15:0,  // 最高达到的小关下标: 0的话，指的是第一小关
    
    bigChapterNumber:1,  // 玩家当前所选的大关卡
    smallChapterNumber:1,  // 当前所选的小关卡


    result:null, //当前关卡的答案

    chapterAnimals:[  // 动物的顺序最好不要修改
        {
            filename:"cat",
            name:"猫咪"
        },
        {
            filename:"cow",
            name:"牛仔"
        },
        {
            filename:"frog",
            name:"青蛙王子"
        },
        {
            filename:"husky",
            name:"哈士奇"
        },
        {
            filename:"koala",
            name:"考拉"
        },
        {
            filename:"kumamon",
            name:"熊本熊"
        },
        {
            filename:"lion",
            name:"狮子"
        },
        {
            filename:"owl",
            name:"猫头鹰"
        },
        {
            filename:"panda",
            name:"熊猫"
        },
        {
            filename:"penguin",
            name:"企鹅"
        },
        {
            filename:"pinkPig",
            name:"粉红猪"
        },
        {
            filename:"rabbit",
            name:"兔子"
        },
        {
            filename:"raccoon",
            name:"小浣熊"
        },
        {
            filename:"sheep",
            name:"绵羊"
        },
        {
            filename:"snowman",
            name:"雪人"
        },
        {
            filename:"sponge",
            name:"海绵宝宝"
        },
        {
            filename:"watermelon",
            name:"西瓜"
        },
        {
            filename:"whiteTiger",
            name:"白虎"
        },
        {
            filename:"wukong",
            name:"孙悟空"
        },
        {
            filename:"yellowChick",
            name:"小黄鸡"
        },
    ],


    animalHeadAnimationsKey:{
        "cat":"3-1",
        "cow":"18-1",
        "frog":"17-1",
        "husky":"12-1",
        "koala":"9-1",
        "kumamon":"14-1",
        "lion":"13-1",
        "owl":"8-1",
        "panda":"7-1",
        "penguin":"4-1",
        "pinkPig":"11-1",
        "rabbit":"19-1",
        "raccoon":"16-1",
        "sheep":"1-1",
        "snowman":"10-1",
        "sponge":"2-1",
        "watermelon":"5-1",
        "whiteTiger":"20-1",
        "wukong":"6-1",
        "yellowChick":"15-1"
    },



    getHeadAnimations(animalName){
        return this.animalHeadAnimationsKey[animalName];
    },

    // ================ 方法部分 =================
    getAnimalName(){
        return this.chapterAnimals[this.bigChapterNumber - 1].filename;
    },
    playAudio(audio){
        if(this.canPlayAudio){
            cc.audioEngine.playEffect(audio,false);
            // let audioId = cc.audioEngine.play(audio,false,1);
            // cc.audioEngine.setFinishCallback(audioId, function () {
            //     cc.audioEngine.stop(audioId);
            // });
        }
    },
};